package cn.hairui.blog.controller;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.entity.Myinfo;
import cn.hairui.blog.entity.SRescManage;
import cn.hairui.blog.entity.SRescMenu;
import cn.hairui.blog.entity.User;
import cn.hairui.blog.service.MyinfoService;
import cn.hairui.blog.service.SRescManageService;
import cn.hairui.blog.service.SRescMenuService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
public class ManageIndexController {
    @Autowired
    private MyinfoService myinfoService;

    @Autowired
    private SRescManageService sRescManageService;
    @Autowired
    private SRescMenuService sRescMenuService;

    @RequestMapping(value = "/manage", method = RequestMethod.GET)
    public String manage(HttpServletRequest request, Model model) {

        Map map = new HashMap<>() ;
        User user = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (user == null || !PubConstant.USER_TYPE_SUPER_ADMIN.equals(user.getType())) {
            return "redirect:/error/403";
        }
        map.put("USE_FLAG", PubConstant.YES_NO_Y);
        Myinfo myinfo = myinfoService.getById(PubConstant.MY_INFO_ID);
        model.addAttribute("myinfo", myinfo);
        List<SRescManage> sRescManageList = (List<SRescManage>) sRescManageService.listByMap(map);
        model.addAttribute("sRescManages", sRescManageList);
        return "page/index";
    }

    @RequestMapping(value = "/manage/main", method = RequestMethod.GET)
    public String main() {
        return "page/main";
    }

    @RequestMapping(value = "/manage/navs")
    @ResponseBody
    public String navs() {
        // 获取左侧菜单
        List<SRescManage> mgrRescList = sRescManageService
                .selectByUseFlagOrder(PubConstant.YES_NO_Y);
        Iterator iterator = mgrRescList.iterator();
        Map result = new HashMap();
        while (iterator.hasNext()) {
            SRescManage sRescManage = (SRescManage) iterator.next();
            List<SRescMenu> mgrRescmenuList = sRescMenuService
                    .selectByRescIdUseFlagOrder(sRescManage.getRescId(), PubConstant.YES_NO_Y);
            result.put(sRescManage.getRescId(), mgrRescmenuList);
        }
        JSONObject json = new JSONObject(result);
        return json.toString();
    }

    @RequestMapping(value = "/manage/parameter", method = RequestMethod.GET)
    public String parameter() {
        return "page/parameter";
    }
}
